Skip to content
Built 26/04/17 09:39commit 8de3d61

中文 | English

非交互模式允许你在不打开交互式 TUI 的情况下,从脚本(例如持续集成(CI)任务)中运行 Codex。调用方式是 codex exec

关于各个 flag 的细节,请参阅 codex exec

何时使用 codex exec

当你希望 Codex:

  • 作为流水线的一部分运行(CI、合并前检查、定时任务)。
  • 生成可被其他工具继续处理的输出(例如生成发布说明或摘要)。
  • 自然地融入 CLI 工作流,将命令输出传给 Codex,再把 Codex 输出传给其他工具。
  • 在明确预设好的沙箱与审批设置下运行。

这时就使用 codex exec

基本用法

将任务提示作为单个参数传入:

bash
codex exec "summarize the repository structure and list the top 5 risky areas"

codex exec 运行期间,Codex 会将进度流式输出到 stderr,并仅将最终 agent 消息打印到 stdout。这使得你可以方便地重定向或管道化最终结果:

bash
codex exec "generate release notes for the last 10 commits" | tee release-notes.md

如果你不想将 session rollout 文件持久化到磁盘,请使用 --ephemeral

bash
codex exec --ephemeral "triage this repository and suggest next steps"

如果 stdin 是通过管道传入,且你同时提供了一个 prompt 参数,Codex 会把 prompt 视为指令,把管道输入内容视为附加上下文。

这使得你可以很方便地先用一个命令生成输入,再直接交给 Codex:

bash
curl -s https://jsonplaceholder.typicode.com/comments \
  | codex exec "format the top 20 items into a markdown table" \
  > table.md

有关更高级的 stdin 管道模式,请参阅 Advanced stdin piping

权限与安全

默认情况下,codex exec 在只读沙箱中运行。在自动化场景中,请设置该工作流所需的最小权限:

  • 允许编辑:codex exec --full-auto "<task>"
  • 允许更广泛访问:codex exec --sandbox danger-full-access "<task>"

只有在受控环境中(例如隔离的 CI runner 或容器)才应使用 danger-full-access

如果你配置了一个已启用且 required = true 的 MCP server,而它初始化失败,那么 codex exec 会直接以错误退出,而不是在缺少该 server 的情况下继续运行。

让输出可供机器读取

如果你想在脚本中消费 Codex 的输出,请使用 JSON Lines 输出:

bash
codex exec --json "summarize the repo structure" | jq

启用 --json 后,stdout 会变成 JSON Lines(JSONL)流,这样你就可以捕获 Codex 在运行期间发出的每个事件。事件类型包括 thread.startedturn.startedturn.completedturn.faileditem.*error

Item 类型包括 agent 消息、推理、命令执行、文件变更、MCP 工具调用、网页搜索以及 plan 更新。

示例 JSON 流(每一行都是一个 JSON 对象):

jsonl
{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
{"type":"turn.started"}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Repo contains docs, sdk, and examples directories."}}
{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122}}

如果你只需要最终消息,可使用 -o <path> / --output-last-message <path> 将其写入文件。该选项会把最终消息写入文件,同时仍将其打印到 stdout(详见 codex exec)。

使用 schema 创建结构化输出

如果你的下游步骤需要结构化数据,请使用 --output-schema 来请求一个符合 JSON Schema 的最终响应。这对需要稳定字段的自动化工作流非常有用(例如任务摘要、风险报告或发布元数据)。

schema.json

json
{
  "type": "object",
  "properties": {
    "project_name": { "type": "string" },
    "programming_languages": {
      "type": "array",
      "items": { "type": "string" }
    }
  },
  "required": ["project_name", "programming_languages"],
  "additionalProperties": false
}

使用该 schema 运行 Codex,并将最终 JSON 响应写入磁盘:

bash
codex exec "Extract project metadata" \
  --output-schema ./schema.json \
  -o ./project-metadata.json

示例最终输出(stdout):

json
{
  "project_name": "Codex CLI",
  "programming_languages": ["Rust", "TypeScript", "Shell"]
}

在 CI 中认证

codex exec 默认会复用已保存的 CLI 认证信息。在 CI 中,常见做法是显式提供凭据:

  • CODEX_API_KEY 设置为该任务的 secret 环境变量。
  • 牢记 prompts 与工具输出:它们可能包含敏感代码或数据。

如果你想仅在单次运行中使用不同的 API key,可以内联设置 CODEX_API_KEY

bash
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"

CODEX_API_KEY 仅在 codex exec 中受支持。

在 CI/CD 中使用 ChatGPT 管理的认证(高级)

如果你需要在 CI/CD 任务中使用 Codex 用户账号而不是 API key 运行,例如企业团队在受信任 runner 上使用由 ChatGPT 管理访问权限的 Codex,或者用户需要使用 ChatGPT/Codex 限流而不是 API key 额度,请阅读这一部分。

对于自动化来说,API key 是默认的正确选择,因为它更容易发放与轮换。只有在你明确需要以 Codex 账号身份运行时,才使用这条路径。

请像对待密码一样对待 ~/.codex/auth.json:它包含访问令牌。不要提交它,不要把它贴到工单里,也不要在聊天中分享它。

不要在公开或开源仓库中使用这一工作流。如果 runner 上无法执行 codex login,请通过安全存储下发 auth.json,在 runner 上运行 Codex 以便 Codex 原地刷新该文件,并在多次运行之间持久化更新后的文件。

请参阅 Maintain Codex account auth in CI/CD (advanced)

恢复非交互式会话

如果你需要继续前一次运行(例如两阶段流水线),请使用 resume 子命令:

bash
codex exec "review the change for race conditions"
codex exec resume --last "fix the race conditions you found"

你也可以通过 codex exec resume <SESSION_ID> 指定某个具体 session ID。

必须位于 Git 仓库中

Codex 要求命令必须在 Git 仓库内运行,以防止破坏性更改。如果你确信环境安全,可以使用 codex exec --skip-git-repo-check 覆盖此检查。

常见自动化模式

示例:在 GitHub Actions 中自动修复 CI 失败

你可以使用 codex exec 在 CI workflow 失败时自动提出修复。典型模式是:

  1. 当主 CI workflow 以错误结束时,触发一个后续 workflow。
  2. 检出失败提交的 SHA。
  3. 安装依赖,并以一个范围很窄的 prompt 和最小权限运行 Codex。
  4. 重新执行测试命令。
  5. 用产生的补丁打开一个 pull request。

使用 Codex CLI 的最小工作流

下面的示例展示了核心步骤。请根据你的技术栈调整安装与测试命令。

yaml
name: Codex auto-fix on CI failure

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

permissions:
  contents: write
  pull-requests: write

jobs:
  auto-fix:
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    runs-on: ubuntu-latest
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      FAILED_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
      FAILED_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ env.FAILED_HEAD_SHA }}
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install dependencies
        run: |
          if [ -f package-lock.json ]; then npm ci; else npm i; fi

      - name: Install Codex
        run: npm i -g @openai/codex

      - name: Authenticate Codex
        run: codex login --api-key "$OPENAI_API_KEY"

      - name: Run Codex
        run: |
          codex exec --full-auto --sandbox workspace-write \
            "Read the repository, run the test suite, identify the minimal change needed to make all tests pass, implement only that change, and stop. Do not refactor unrelated files."

      - name: Verify tests
        run: npm test --silent

      - name: Create pull request
        if: success()
        uses: peter-evans/create-pull-request@v6
        with:
          branch: codex/auto-fix-${{ github.event.workflow_run.run_id }}
          base: ${{ env.FAILED_HEAD_BRANCH }}
          title: "Auto-fix failing CI via Codex"

替代方案:使用 Codex GitHub Action

如果你想避免自己安装 CLI,可以通过 Codex GitHub Action 运行 codex exec,并把 prompt 作为输入传入。

高级 stdin 管道模式

当另一个命令为 Codex 生成输入时,请根据指令应来自哪里来选择 stdin 模式。如果你已经知道指令是什么,并且只想把管道输出作为上下文传入,请使用 prompt-plus-stdin。若 stdin 本身就应成为完整 prompt,请使用 codex exec -

使用 prompt-plus-stdin

当另一个命令已经产出了你希望 Codex 检查的数据时,prompt-plus-stdin 很有用。在这种模式下,你自己编写指令,再把命令输出通过管道传入作为上下文,因此它非常适合围绕命令输出、日志和生成数据构建的 CLI 工作流。

bash
npm test 2>&1 \
  | codex exec "summarize the failing tests and propose the smallest likely fix" \
  | tee test-summary.md

更多 prompt-plus-stdin 示例

总结日志

bash
tail -n 200 app.log \
  | codex exec "identify the likely root cause, cite the most important errors, and suggest the next three debugging steps" \
  > log-triage.md

检查 TLS 或 HTTP 问题

bash
curl -vv https://api.example.com/health 2>&1 \
  | codex exec "explain the TLS or HTTP failure and suggest the most likely fix" \
  > tls-debug.md

准备适合发到 Slack 的更新

bash
gh run view 123456 --log \
  | codex exec "write a concise Slack-ready update on the CI failure, including the likely cause and next step" \
  | pbcopy
bash
gh run view 123456 --log \
  | codex exec "summarize the failure in 5 bullets for the pull request thread" \
  | gh pr